<?
global $db,$user;
$pid = $db->sqlint($params["id"]);
$uid = $db->sqlint($user["id"]);

$file = $_FILES["file"];
$fname = $file["tmp_name"];

$lines = file($fname);
$line = chop(array_shift($lines));
$fields = explode("\t",$line);

$map = array(
	"Unique_ID"=>"importid",#"msp_Unique_ID",
	"Task_Name"=>"title",
	"Notes"=>"description",
	"ID"=>"displayid",#"msp_ID",
	"WBS"=>"wbs",#"msp_WBS",
	#"Milestone"=>"msp_Milestone",
	#"Summary"=>"msp_Summary",
	#"Duration"=>"duration",#"msp_Duration",
	"Start_Date"=>"datestart",#"msp_Start_Date",
	"Finish_Date"=>"dateend",#"msp_Finish_Date",
	"Outline_Level"=>"level",#"msp_Outline_Level",
	#"Percent_Complete"=>"percent",
	 );
	
foreach ($lines as $line) {
	$parts = explode("\t",chop($line));
	$e = array();
	foreach ($fields as $k=>$v) $e[$v] = $parts[$k];
	
	#modules_id
	$v=$e["Text1"]; if (!$v) $v="-- n/a --";
	$r = $db->query("select * from modules where project_id = $pid or id < 0 and title = ".$db->sqlstring($v));
	if (count($r)) { $ee = array_pop($r); $mid = $ee["id"]; }
		else { $mid = $db->autoquery("insert","modules",array(
			"project_id"=>$pid,"title"=>$v)); }
			
	#id
	$r = $db->query("select * from task where project_id = $pid and importid = ".$db->sqlint($v=$e["Unique_ID"]));
	if (count($r)) { $ee = array_pop($r); $id = $ee["id"]; }
		else { $id = "new"; }
		
	#aid
	$r = $db->query("select * from users where name = ".$db->sqlstring($v=$e["Resource_Names"]));
	if (count($r)) { $ee = array_pop($r); $aid = $ee["id"]; }
		else { $aid = -1; }

	#status
	#$v = $e["Percent_Complete"];
	#$status = (intval($v)==100?"finished":"unfinished");
		
	#create record
	$ee = array(
		"id"=>$id,
		"project_id"=>$pid,
		"submit_users_id"=>$uid,
		"modules_id"=>$mid,
		"assign_users_id"=>$aid,
		#"status"=>$status,
		);
	$e["Start_Date"] = date("Y-m-d",strtotime($e["Start_Date"]));
	$e["Finish_Date"] = date("Y-m-d",strtotime($e["Finish_Date"]));
	$e["Percent_Complete"] = intval($e["Percent_Complete"]);
	foreach ($map as $k=>$v) $ee[$v] = $e[$k];
	
	if ($id == "new") {
		unset($ee["id"]);
		$ee["status"] = "open";
		if ($e["Percent_Complete"] == 100) 
			$ee["status"] = "closed";
		$ee["priority"] = 3;
		$db->autoquery("insert","task",$ee); 
		}
	else {
		if ($e["Percent_Complete"] == 100) 
			$ee["status"] = "closed";
		$db->autoquery("update","task",$ee);
		}
	}

header("Location: ../index.php"); die;
?>